﻿using System;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using QAHelper.Common;
using WatiNTest;
using Logger;

namespace TestHarness_GUI
{
    public static class TestRunner
    {
        public static TestCaseStructure testCaseStructure = null;
        public static ArrayList headerList = null;
        public static DataGridView dgv = null;
        public static TreeView treeLogFiles = null;

        [STAThread]
        public static void Execute(string dataFileDir, string logDestDir, string browserType, string urlToTest)
        {
            DataGridViewRow dgvRow = new DataGridViewRow();
            DataGridViewColumn dgvClm = new DataGridViewColumn();


            int rowIndex = dgv.Rows.Add(dgvRow);
            dgv.Rows[rowIndex].Cells[0].Value = "Initiating Environment";
                        

            string thisDateTime = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
            string testScriptDir = dataFileDir;//Properties.Settings.Default.TEST_SCRIPT_DIRECTORY;
            string traceLogFileName = logDestDir + @"Test_Execution_TraceLog_" + DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss") + ".log";
            TestManager.traceLogFileName = traceLogFileName;
            TestManager.BROWSER_TYPE = browserType;//Properties.Settings.Default.BROWSER_TYPE;
            TestManager.URL_TO_TEST = urlToTest;// Properties.Settings.Default.TEST_URL;

            if (!Directory.Exists(Directory.GetParent(logDestDir).Name))
                Directory.CreateDirectory(Directory.GetParent(logDestDir).Name);


            if (!Directory.Exists(logDestDir.Trim()))
                Directory.CreateDirectory(logDestDir.Trim());

            string logDir = logDestDir; //+ DateTime.Now.ToString("MM_dd_yyyy_hh_mm");

            dgvRow = UpdateDataGridView(dgv, dgvRow, rowIndex,"1");
            try
            {
                
                Console.WriteLine("{0} Starting TestHarness for WatiN.............", thisDateTime);
                File.AppendAllText(traceLogFileName, string.Format("{0} Starting TestHarness for WatiN............."+Environment.NewLine, thisDateTime));

                if (!string.IsNullOrEmpty(testScriptDir))
                {

                    rowIndex = dgv.Rows.Add(dgvRow);
                    dgv.Rows[rowIndex].Cells[0].Value = "Reading files from "+testScriptDir;                        

                    string[] fileNames = Directory.GetFiles(testScriptDir);
                    DirectoryInfo directoryInfo = new DirectoryInfo(testScriptDir);
                    
                    FileSystemInfo[] fileInfos = directoryInfo.GetFileSystemInfos();

                    dgvRow = UpdateDataGridView(dgv, dgvRow, rowIndex,"1");

                    int rowIndexFiles = dgv.Rows.Add(dgvRow);
                    dgv.Rows[rowIndexFiles].Cells[0].Value = string.Format("Traversing through  total {0} test script files", fileInfos.Length);

                    foreach (string fileName in fileNames)
                    {
                        string[] extensionArray = fileName.Split('.');
                        string extension = extensionArray[1];
                        if (!extension.Equals("xls"))
                            continue;
                        testCaseStructure = new TestCaseStructure();
                        headerList = new ArrayList();

                        FileInfo fileInfo = new FileInfo(fileName);
                        string className = fileInfo.Name.Replace("_", "").Split('.')[0];

                        if (className.Contains("-"))
                            className = className.Replace("-", "");

                        DataGridViewRow testFileRow = new DataGridViewRow();
                        rowIndex = dgv.Rows.Add(testFileRow);
                        dgv.Rows[rowIndex].Cells[0].Value = string.Format("Reading Test Scenarios from {0}", fileName);


                        Console.WriteLine("\n{0} Reading Test Scenarios from {1}.............", thisDateTime, fileName);
                        File.AppendAllText(traceLogFileName, string.Format(Environment.NewLine+"{0} Reading Test Scenarios from {1}............." + Environment.NewLine, thisDateTime, fileName));

                        ExcelReader reader = new ExcelReader();
                        HtmlLogger logger = new HtmlLogger();

                        testCaseStructure.TestCaseFileName = fileName;
                        testCaseStructure.TestCaseWorkSheetName = "Test_Plan";
                        /*testCaseStructure.TestLogFileName = logDestDir +
                                                            className + "_" +
                                                            DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss") + ".xls";*/

                        testCaseStructure = reader.ReadInputFromFile(testCaseStructure, out headerList, 10);


                        Console.WriteLine("{0} End of Reading Test Scenarios from {1}.............", thisDateTime, fileName);
                        File.AppendAllText(traceLogFileName, string.Format("{0} End of Reading Test Scenarios from {1}............." + Environment.NewLine, thisDateTime, fileName));

                        dgvRow = UpdateDataGridView(dgv, testFileRow, rowIndex, "1");

                        testFileRow = new DataGridViewRow();
                        rowIndex = dgv.Rows.Add(testFileRow);
                        dgv.Rows[rowIndex].Cells[0].Value = string.Format("Starting Execution of {0}.............", className);
                        Console.WriteLine("{0} Starting Execution of {1}.............", thisDateTime, className);
                        File.AppendAllText(traceLogFileName, string.Format("{0} Starting Execution of {1}............." + Environment.NewLine, thisDateTime, fileName));

                        Type typeOfClass = null;

                        object instanceOfClass = CommonHelper.GetInvokerType(Properties.Settings.Default.NAMESPACE, className, out typeOfClass, testCaseStructure,headerList);

                        for (int i = 0; i < testCaseStructure.TestScenarios.Count; i++)
                        {
                            TestScenario scenario = (TestScenario)testCaseStructure.TestScenarios[i];

                            if (!string.IsNullOrEmpty(scenario.SkipExecution))
                            {
                                if (scenario.SkipExecution.Equals("0")
                                    || scenario.SkipExecution.Equals("False", StringComparison.InvariantCultureIgnoreCase)
                                    || scenario.SkipExecution.Equals("F", StringComparison.InvariantCultureIgnoreCase)
                                    || scenario.SkipExecution.Equals("No", StringComparison.InvariantCultureIgnoreCase)
                                    || scenario.SkipExecution.Equals("N", StringComparison.InvariantCultureIgnoreCase)
                                   )
                                {
                                    if (!string.IsNullOrEmpty(scenario.TestCaseID))
                                    {
                                        DataGridViewRow dgvScenarioRow = new DataGridViewRow();
                                        int rowIndexS = dgv.Rows.Add(dgvScenarioRow);
                                        dgv.Rows[rowIndexS].Cells[0].Value = string.Format("\t Starting Execution of {0}..........................", scenario.TestCaseID);

                                        Console.WriteLine("\n\t{0} Starting Execution of {1}.............", thisDateTime, scenario.TestCaseID);
                                        File.AppendAllText(traceLogFileName, string.Format(Environment.NewLine + "\t{0} Starting Execution of {1}............." + Environment.NewLine, thisDateTime, scenario.TestCaseID));
                                        TestManager.InvokeTestMethod(scenario.TestCaseID, typeOfClass, instanceOfClass, scenario);
                                        Console.WriteLine(" \t{0} End of Execution of {1}.............", thisDateTime, scenario.TestCaseID);
                                        File.AppendAllText(traceLogFileName, string.Format("\t{0} End of Execution of {1}............." + Environment.NewLine, thisDateTime, scenario.TestCaseID));
                                        dgvRow = UpdateDataGridView(dgv, dgvScenarioRow, rowIndexS, scenario.Status);
                                    }
                                }
                                else
                                {
                                    scenario.Status = "Skipped";
                                    scenario.ObservedResult = "Skipped";
                                }
                            }
                        }
                        dgvRow = UpdateDataGridView(dgv, testFileRow, rowIndex, "1");
                        dgvRow = UpdateDataGridView(dgv, dgvRow, rowIndexFiles, "1");

                        Console.WriteLine("{0} \nEnd of Execution of {1}.............", thisDateTime, className);
                        File.AppendAllText(traceLogFileName, string.Format(Environment.NewLine+"{0} End of Execution of {1}............." + Environment.NewLine, thisDateTime, className));
                        Console.WriteLine("{0} Writting log file {1}.html:............." + Environment.NewLine, thisDateTime,className);
                        File.AppendAllText(traceLogFileName, string.Format("{0} Writting log file {1}.html:............." + Environment.NewLine,thisDateTime, className));
                        logger.WriteToFile(testCaseStructure.TestScenarios, logDir, Properties.Settings.Default.LOG_ASSETS_URL.Trim(),className);
                        treeLogFiles.Nodes.Add(className + ".html");
                        
                    }
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine("{0} Unexpected error occurred. Error is:  {1}.............", thisDateTime, exp.Message);
                File.AppendAllText(traceLogFileName, string.Format("{0} Unexpected error occurred. Error is: {1}............." + Environment.NewLine, thisDateTime, exp.Message));
            }
            finally
            {

                Console.WriteLine("{0} End of Executing all test cases. Shutting down TestHarness for WatiN.............", thisDateTime);
                File.AppendAllText(traceLogFileName, string.Format("{0} End of Executing all test cases. Shutting down TestHarness for WatiN............." + Environment.NewLine, thisDateTime));
            }
        }

        private static DataGridViewRow UpdateDataGridView(DataGridView dgv, DataGridViewRow dgvRow, int rowIndex, string status)
        {
            if (status.Equals("Pass") || status.Equals("1"))
            {
                dgv.Rows[rowIndex].Cells[1].Value = Properties.Resources.tick;
                dgv.Rows[rowIndex].Cells[1].ToolTipText = "Pass";
            }
            else
            {
                dgv.Rows[rowIndex].Cells[1].Value = Properties.Resources.fail;
                dgv.Rows[rowIndex].Cells[1].ToolTipText = "Fail";
            }
            dgv.Refresh();
            dgvRow.Dispose();
            dgvRow = new DataGridViewRow();
            return dgvRow;

        }
    }    
}
